import datetime
from datetime import timedelta

from app.monitor_doris.handlers.monitor_doris_service_handler import MonitorDorisServiceHandler
from app.monitor_doris.handlers.monitor_doris_custom_handler import MonitorDorisCustomHandler
from app.monitor_doris.handlers.monitor_doris_http_record_handler import MonitorDorisHttpRecordHandler
from app.monitor_doris.handlers.monitor_doris_http_check_handler import MonitorDorisHttpCheckHandler
from common.database import SessionLocal
from core.celery import celery_app, TaskMonitor
from app.celery_task.models.celery_task import CeleryTask
from core.logger import logger




@celery_app.task(base=TaskMonitor, bind=True)
def monitor_doris_check_service(self, interval_min=5):
    """
    检查服务错误日志的异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()
    
    # 开始事件
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => progress failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        monitor_doris_service_handler = MonitorDorisServiceHandler()
        result = monitor_doris_service_handler.task_check_services_handle(session, interval_min)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True



@celery_app.task(base=TaskMonitor, bind=True)
def monitor_doris_check_custom(self):
    """
    检查服务自定义告警的异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()
    
    # 开始事件
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => progress failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        monitor_doris_custom_handler = MonitorDorisCustomHandler()
        result = monitor_doris_custom_handler.task_check_custom_handle(session)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True





@celery_app.task(base=TaskMonitor, bind=True)
def monitor_doris_http_check(self, interval_min=5):
    """
    检查http请求状态告警异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()

    # 开始事件
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => progress failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        monitor_doris_http_check_handler = MonitorDorisHttpCheckHandler()
        result = monitor_doris_http_check_handler.task_http_check_handle(session, interval_min)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True




@celery_app.task(base=TaskMonitor, bind=True)
def monitor_doris_http_record(self, interval_min=5):
    """
    更新http请求的记录信息异步任务
    """

    # 获取任务信息
    tid = self.request.id
    task_name = self.name.split(".")[-1]
    session = SessionLocal()

    # 开始事件
    try:
        # 检查数据库任务信息是否创建
        result = CeleryTask.check_object_by_tid(session, tid)
        if not result:
            logger.error(f"tid:{tid} => progress failed, database info not exist")
            return False

        # 更新状态
        CeleryTask.update_task(session, tid, state="PROGRESS")

        # 启动任务
        monitor_doris_http_record_handler = MonitorDorisHttpRecordHandler()
        result = monitor_doris_http_record_handler.task_update_from_doris_handle(session, interval_min)
        if not result:
            logger.error(f"tid:{tid} => {task_name} failed")
            return False
    except Exception as e:
        logger.exception(f"tid:{tid} => {task_name} error=> {e}")
        return False
    finally:
        session.close()

    # 更新完成
    logger.info(f"tid:{tid} => {task_name} success")
    return True


            
    

if __name__ == '__main__':
    monitor_logs_abnormal_application_notice()
